import { useLocation } from "react-router-dom";
import { Navigate } from "react-router-dom";

//高阶组件，控制路由权限(未登录时，强制跳转到登录页面；登录时，可以访问除登录和注册以外的页面)
const AuthRoute = ({ children }) => {
  const isLogin = localStorage.getItem("isLogin") || 0;
  const location = useLocation();
  const menuList = JSON.parse(localStorage.getItem("menuList")) || [];
  const whiteList = [
    "/login",
    "/register",
    "/notFound",
    "/loginFailure",
    "/",
  ];
  let allowRoute = [];
  const getAllowRoute = (arr) => {
    arr.forEach((e) => {
      if (e.key) {
        allowRoute.push(e.key);
      }
      if (e.children) {
        getAllowRoute(e.children);
      }
    });
  };
  getAllowRoute(menuList);
  allowRoute = [...new Set(allowRoute)];
  if (
    !allowRoute.includes(location.pathname) &&
    !whiteList.includes(location.pathname)
  ) {
    return <Navigate to="/notFound" replace />;
  }

  if (
    Number(isLogin) === 1 &&
    location.pathname !== "/login" &&
    location.pathname !== "/register"
  ) {
    return <>{children}</>;
  } else if (
    Number(isLogin) === 1 &&
    (location.pathname === "/login" || location.pathname === "/register")
  ) {
    return <Navigate to="/" replace />;
  } else if (
    Number(isLogin) === 0 &&
    (location.pathname === "/login" || location.pathname === "/register")
  ) {
    return <>{children}</>;
  } else {
    return <Navigate to="/login" replace />;
  }
};

export default AuthRoute;
